package com.flycent.hqhs.http;
import static com.flycent.hqhs.Constants.REST_CODE;
import static com.flycent.hqhs.Constants.REST_CONTENT;
import static com.flycent.hqhs.http.WebException.TYPE_CHECK_NETWORK;
import static com.flycent.hqhs.http.WebException.TYPE_ERROR_NETWORK;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Arrays;

import android.content.Context;
import android.util.Log;

import com.flycent.hqhs.ui.BaseActivity;
import com.flycent.hqhs.util.NetworkUtil;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

// HttpURLConnection
public class WebHelper {

	public static final String TAG = "WebHelper";
	
	long date = -1; // 时间戳
	
	private static WebHelper instance 	= null;

	private Context context 			= null;
	private String UUID 				= null;
	
	static{
		CookieHandler.setDefault(new CookieManager());
	}
	
	private WebHelper(Context context) {
		super();
		this.context = context;
		UUID = BaseActivity.getUUID(context);
	}

	/** 获取WebHelper */
	static WebHelper getInstance(Context context) {
		if (null == instance) {
			instance = new WebHelper(context);
			return instance;
		}
		return instance;
	}
	
	//---------------------------------------------------
	
	/**@param url 请求地址
	 * @param method 请求方式：[OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE]
	 * @throws WebException */
	protected String doRequest(String url, String method) throws WebException {
		
		if (!NetworkUtil.isNetworkConnected(context)) {							// 判断是否联网
			throw new WebException(context, TYPE_CHECK_NETWORK);
		}
		
		if (!isPermittedUserMethod(method)) 						// 判断请求方式
			throw new IllegalArgumentException("Unknown method '" + method + "'; must be one of " + Arrays.toString(PERMITTED_USER_METHODS));

		
		Log.d(TAG, "url address:  " + url);
		
		try {
			URL u = new URL(url);

			HttpURLConnection conn = null;
			if (method.equals("POST") && url.contains("?"))
				conn = (HttpURLConnection) new URL(url.substring(0, url.lastIndexOf("?"))).openConnection();
			else
				conn = (HttpURLConnection) u.openConnection();

			conn.setRequestMethod(method);
			conn.setRequestProperty("X-Ticket", UUID);

			if ("POST".equals(method)) {
				conn.setDoOutput(true);
				OutputStream outStream = conn.getOutputStream();
				outStream.write(null == u.getQuery() ? "".getBytes() : u.getQuery().getBytes());
				outStream.flush();
				outStream.close();
			}
			
			// 响应200、400、500
			int statusCode = conn.getResponseCode();
			
			Log.d(TAG, "Server Status Code: " + statusCode );
			
			if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_BAD_REQUEST 
					|| statusCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
				
				date = conn.getHeaderFieldDate("Date", -1);
				
				StringBuilder result = new StringBuilder();

				InputStream in = statusCode == HttpURLConnection.HTTP_OK ? conn.getInputStream() : conn.getErrorStream();
				InputStreamReader inReader = new InputStreamReader(in); 							// 使用UTF-8，和服务端一致，否则会乱码
				BufferedReader bufferedReader = new BufferedReader(inReader); 						// BufferedReader
				String readLine = null;
				while ((readLine = bufferedReader.readLine()) != null)
					result.append(readLine);
				
				in.close();
				inReader.close();
				bufferedReader.close();
				conn.disconnect();
				
				
				Log.d(TAG, "Server Response: " + result);
				
				// 400、500
				if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST || statusCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
					
					Log.d(TAG, "Start Json Parsing ....");
					
					JsonObject obj = new JsonParser().parse(result.toString()).getAsJsonObject();
					
					if ("shop.common.unauthorized".equals(obj.get(REST_CODE).getAsString())) { // 未登录, 设置Cookie
						
//						List<HttpCookie> cookies = new ArrayList<>();
//						String cookieString = null;
//						if (null != (cookieString = conn.getHeaderField("Set-Cookie")))
//							cookies.addAll(HttpCookie.parse(cookieString));
//						if (null != (cookieString = conn.getHeaderField("Set-Cookie2")))
//							cookies.addAll(HttpCookie.parse(cookieString));
//						
//						CookieManager manager = (CookieManager) CookieHandler.getDefault();
//						CookieStore store = manager.getCookieStore();
//						for (HttpCookie cookie : cookies)
//							store.add(null, cookie);
//						CookieHandler.setDefault(manager);
					}
					
					throw new WebException(context, obj.get(REST_CODE).getAsString(), obj.get(REST_CONTENT).getAsString());
				}
				
				return result.toString();
				
			} else {
				
				//Receive other status code....
				throw new WebException(context, statusCode + "");
			}
			
		} catch (MalformedURLException | ProtocolException e) {
			Log.e(TAG, e.toString());
		} catch (IOException e) {
			Log.e(TAG, e.toString());
		}
		
		throw new WebException(context, TYPE_ERROR_NETWORK);
	}
	
	//	Check HTTP Method ----------------------------------------

	/** HTTP methods */
	private static final String[] PERMITTED_USER_METHODS = {
		"OPTIONS",
		"GET",
		"HEAD",
		"POST",
		"PUT",
		"DELETE",
		"TRACE"
	};

	/** 判断是否是允许的请求方式 */
	private boolean isPermittedUserMethod(String method) {
		for (String permittedUserMethod : PERMITTED_USER_METHODS)
			if (permittedUserMethod.equals(method))
				return true;

		return false;
	}
	
}